/*
 * Copyright (C) 2015 yixun All Rights Reserved.
 * 
 * PartnerInfoController.java
 */
package com.yixun.qfbao.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.yixun.qfbao.model.enums.DelFlagEnum;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.yixun.common.controller.BaseController;
import com.yixun.common.exception.YIXUNExceptionCode;
import com.yixun.common.exception.YIXUNUNCheckedException;
import com.yixun.common.page.Page;
import com.yixun.common.page.PageUtil;
import com.yixun.qfbao.controller.vo.PartnerInfoVo;
import com.yixun.qfbao.model.Department;
import com.yixun.qfbao.model.Dictionary;
import com.yixun.qfbao.model.PartnerInfo;
import com.yixun.qfbao.model.PasswordUtil;
import com.yixun.qfbao.model.dto.DepartmentDto;
import com.yixun.qfbao.model.dto.DictionaryDto;
import com.yixun.qfbao.model.dto.PartnerInfoDto;
import com.yixun.qfbao.model.enums.DictionaryTypeEnum;
import com.yixun.qfbao.model.enums.MechanismAccountTypeEnum;
import com.yixun.qfbao.model.enums.MechanismStatusEnum;
import com.yixun.qfbao.service.CompanyService;
import com.yixun.qfbao.dao.DepartmentDao;
import com.yixun.qfbao.service.DictionaryService;
import com.yixun.qfbao.service.PartnerInfoService;

/**
 * [文件名称]<br>
 * PartnerInfoController.java<br>
 * <br>
 * [文件描述]<br>
 * 合作机构 Controller<br>
 * <br>
 * [修改记录]<br>
 * 2015-10-13 15:32:11 创建 陶俊代码生成器<br>
 * 
 * @author 陶俊代码生成器
 * @version 1.00
 */
@Controller
@RequestMapping("/qfbao/partnerinfo")
public class PartnerInfoController extends BaseController {
	@Autowired
	private PartnerInfoService mservice;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private DepartmentDao departmentDao;
	
	private static Logger log = Logger.getLogger(PartnerInfoController.class);
	
	@RequestMapping({"/manage"})
	public String index(Model model){
		return "/qfbao/partnerInfo/manage";
	}
	@RequestMapping({"/channelManage"})
	public String index2(Model model){
		model.addAttribute("op","channel");
		return "/qfbao/partnerInfo/channel_manage";
	}
	
	@RequestMapping("/list")
	public @ResponseBody Page<PartnerInfo> indexJson(String op,PartnerInfoVo entity,HttpServletResponse response,int page,int rows){
		Page<PartnerInfo> pageModel = null;
		try { 
			PartnerInfoDto en = entity.toDto();
			if("channel".equals(op)){
				en.setCompanyType(Long.parseLong("1"));
			}else{
				en.setCompanyType(Long.parseLong("20"));
			}
			en.setSql("(t.user_roleId !=-1 or t.user_roleId is null)");
			en.setOrders("t.create_time desc");
			pageModel = mservice.getMyPageModel(en,PageUtil.begin(page,rows),rows);
		}catch (YIXUNUNCheckedException e) {
			log.error("分页信息失败",e);
			pageModel = new Page<PartnerInfo>();
			pageModel.setErrorMsg(e.getCode()+":"+e.getOutMsg());
		}catch (Exception e) {
			log.error("分页信息失败",e);
			pageModel = new Page<PartnerInfo>();
			pageModel.setErrorMsg(YIXUNExceptionCode.UNKNOW_EXCEPTON.getDesout());
		}
		return pageModel;
	}
	
	@RequestMapping("/view")
	public String formView(Model model,PartnerInfoVo entity,Long isView,HttpServletResponse response,Boolean isBack) throws IOException{
		try {
			model.addAttribute("isView", isView);
			if(null==entity.getId()){
				model.addAttribute("model",entity);
			}else{
				PartnerInfo partnerInfo = mservice.selectById(entity.getId());
				PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
				BeanUtils.copyProperties(partnerInfo,partnerInfoDto);
				partnerInfoDto.setAccountTypeCN(MechanismAccountTypeEnum.getByNo(partnerInfoDto.getAccountType()).getDes());
				partnerInfoDto.setStatusCN(MechanismStatusEnum.getByNo(partnerInfoDto.getStatus()).getDes());
				model.addAttribute("model",partnerInfoDto);
				//查询公司
				model.addAttribute("company", companyService.selectById(partnerInfo.getHigherid()));
			}
		}catch (YIXUNUNCheckedException e) {
			log.error("创建失败",e);
		}catch (Exception e) {
			log.error("创建失败",e);
		}
		return "/qfbao/partnerInfo/save_edit";
	}
	
	/** 
     * 手机号验证 
     *  
     * @param  str 
     * @return 验证通过返回true 
     */  
    public static boolean isMobile(String str) {   
        Pattern p = null;  
        Matcher m = null;  
        boolean b = false;   
        p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号  
        m = p.matcher(str);  
        b = m.matches();   
        return b;  
    }  
    /** 
     * 电话号码验证 
     *  
     * @param  str 
     * @return 验证通过返回true 
     */  
    public static boolean isPhone(String str) {   
        Pattern p1 = null,p2 = null;  
        Matcher m = null;  
        boolean b = false;    
        p1 = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$");  // 验证带区号的  
        p2 = Pattern.compile("^[1-9]{1}[0-9]{5,8}$");         // 验证没有区号的  
        if(str.length() >9)  
        {   m = p1.matcher(str);  
            b = m.matches();    
        }else{  
            m = p2.matcher(str);  
            b = m.matches();   
        }    
        return b;  
    } 
	
    /** 
     * 校验银行卡卡号 
     * @param cardId 
     * @return 
     */  
    public static boolean checkBankCard(String cardId) {  
          char bit = getBankCardCheckCode(cardId.substring(0, cardId.length() - 1));  
          if(bit == 'N'){  
              return false;  
          }  
          return cardId.charAt(cardId.length() - 1) == bit;  
    }  
     
    /** 
     * 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位 
     * @param nonCheckCodeCardId 
     * @return 
     */  
    public static char getBankCardCheckCode(String nonCheckCodeCardId){  
        if(nonCheckCodeCardId == null || nonCheckCodeCardId.trim().length() == 0  
                || !nonCheckCodeCardId.matches("\\d+")) {  
         //如果传的不是数据返回N  
            return 'N';  
        }  
        char[] chs = nonCheckCodeCardId.trim().toCharArray();  
        int luhmSum = 0;  
        for(int i = chs.length - 1, j = 0; i >= 0; i--, j++) {  
            int k = chs[i] - '0';  
            if(j % 2 == 0) {  
                k *= 2;  
                k = k / 10 + k % 10;  
            }  
            luhmSum += k;             
        }  
        return (luhmSum % 10 == 0) ? '0' : (char)((10 - luhmSum % 10) + '0');  
    }
    
	@RequestMapping("/save_edit")
	public @ResponseBody Map<String,String> saveOrUpdate(Model model,String prePhone,Long preHigherId,String isView,PartnerInfoVo entity,HttpServletResponse response) throws IOException{
		Map<String,String> res = new HashMap<String, String>();
		String errorMsg = null;
		try {
			if(!StringUtils.isNotBlank(entity.getAccountName())){
				res.put("isSuccess", "1");
				res.put("errorMsg","公司名称不能为空!");
				return res;
			}
			if(!StringUtils.isNotBlank(entity.getPhone())){
				res.put("isSuccess", "1");
				res.put("errorMsg","手机不能为空!");
				return res;
			}
			if(!StringUtils.isNotBlank(entity.getAccountType())){
				res.put("isSuccess", "1");
				res.put("errorMsg","账户类型不能为空!");
				return res;
			}
			entity.setStatus("1");
			entity.setIsAdmin("0");
			//编辑模式 如果是编辑信息且自己的手机号码未改变
			if("1".equals(isView)&&!entity.getPhone().equals(prePhone)){
				//判断是否存在该手机号码
				PartnerInfoDto infoDto = new PartnerInfoDto();
				infoDto.setPhone(entity.getPhone());
				infoDto.setAccountType(0+"");
				List<Long> companyIds = mservice.listGroupCompanyIdByCompanyId(entity.getHigherid(), true);
				infoDto.setCompanyIds(companyIds);
				List<PartnerInfo> queryList = mservice.checkRepeat(infoDto);
				if (null != queryList && queryList.size() > 0) {
					res.put("isSuccess", "1");
					res.put("errorMsg", "手机号码已存在!");
					return res;
				}
			}
			Boolean flag = true;
			if((preHigherId!=null&&!preHigherId.equals(entity.getHigherid()))){
				//编辑时并改变公司时
				flag = false;
			}
			if(entity.getId()==null||!flag){
				if(flag&&!StringUtils.isNotBlank(entity.getPassword())){
					res.put("isSuccess", "1");
					res.put("errorMsg","密码不能为空!");
					return res;
				}
				if(flag&&!StringUtils.isNotBlank(entity.getTruePassWord())){
					res.put("isSuccess", "1");
					res.put("errorMsg","确认密码不能为空!");
					return res;
				}
				if(flag&&!entity.getTruePassWord().equals(entity.getPassword())){
					res.put("isSuccess", "1");
					res.put("errorMsg","密码不一致!");
					return res;
				}
				//新增管理员时，判断类型为开发商的是否存在人员的手机号为已启用
				PartnerInfoDto pid = new PartnerInfoDto();
		//		pid.setCompanyType(Long.parseLong("20"));
				pid.setHigherid(entity.getHigherid());
				pid.setPhone(entity.getPhone());
				List<PartnerInfo> list = mservice.checkRepeat(pid);
				if(list.size()>0){
					res.put("isSuccess", "1");
					res.put("errorMsg","手机号已存在，请重新输入手机号");
					return res;
				}
				//新增管理员时，判断此分销商下是否已经存在一个启用的顶级管理员
				PartnerInfoDto pi = new PartnerInfoDto();
				pi.setHigherid(entity.getHigherid());
				pi.setAccountType("0");
				List<PartnerInfo> partnerInfo = mservice.checkRepeat(pi);
				if(partnerInfo!=null&&partnerInfo.size()>0){
					res.put("isSuccess", "1");
					res.put("errorMsg","此公司下已存在一个处于启用状态下的管理员！");
					return res;
				}
				entity.setPassword(PasswordUtil.md5Hex(entity.getPassword()));
				//选择公司后,根据公司ID,获取公司下的第一部门(第一部门及公司)
				DepartmentDto deptDto = new DepartmentDto();
				deptDto.setMerchantId(entity.getHigherid());
				deptDto.setParentId(0L);
				Department dept = departmentDao.selectByDto(deptDto);
				entity.setDeptId(dept.getId());
			}
			int count=mservice.saveOrUpdate(entity);
			if(count>0){
				res.put("isSuccess", "0");
				res.put("errorMsg","保存成功");
			}else{
				res.put("isSuccess", "1");
				res.put("errorMsg","保存失败");
			}
		}catch (Exception e) {
			res.put("isSuccess", "1");
			res.put("errorMsg","保存失败");
			log.error("编辑失败",e);
		}
		return res;
	}
	
	@RequestMapping("/getTypeList")
	public String getTypeList(HttpServletRequest req, HttpServletResponse res) throws IOException{
		String errorMsg = null;
		String data = null;
		try {
		
			
			List<Dictionary> dictionaries = new ArrayList<Dictionary>();
			for (int i = 0; i < MechanismAccountTypeEnum.values().length; i++) {
				Dictionary nary=new Dictionary();
				nary.setDicType(MechanismAccountTypeEnum.values()[i].getNo());
				nary.setDicValue(MechanismAccountTypeEnum.values()[i].getDes());
				dictionaries.add(nary);
			}
			
			data = JSON.toJSONString(dictionaries);
		}catch (Exception e) {
			errorMsg = YIXUNExceptionCode.UNKNOW_EXCEPTON.getDesout();
			log.error("查询账户类型出错，" + errorMsg, e);
		}
		res.getWriter().write(data);
		return null;
	}
	
	@RequestMapping("/getDictionaryList")
	public String getDictionaryList(HttpServletRequest req, HttpServletResponse res) throws IOException{
		String errorMsg = null;
		String data = null;
		try {
			DictionaryDto dictionary = new DictionaryDto();
			dictionary.setDicType(DictionaryTypeEnum.COMPANY_TYPE.getCode());
			List<Dictionary> dictionaries = dictionaryService.selectListByDto(dictionary);
			data = JSON.toJSONString(dictionaries);
		}catch (Exception e) {
			errorMsg = YIXUNExceptionCode.UNKNOW_EXCEPTON.getDesout();
			log.error("查询公司类型出错，" + errorMsg, e);
		}
		res.getWriter().write(data);
		return null;
	}
	
	@RequestMapping("/del")
	public @ResponseBody Map<String,Object> destroy(PartnerInfoVo entity,HttpServletResponse response) throws IOException{
		Map<String,Object> res = new HashMap<String, Object>();
		try {
			int destroyCount = mservice.destroy(entity.toDto());
			res.put("count",destroyCount);
			res.put("row",entity.toDto());
		}catch (YIXUNUNCheckedException e) {
			log.error("删除失败",e);
			res.put("errorMsg",e.getCode()+":"+e.getOutMsg());
		}catch (Exception e) {
			log.error("删除失败",e);
			res.put("errorMsg",YIXUNExceptionCode.UNKNOW_EXCEPTON.getDesout());
		}
		return res;
	}
	
	@RequestMapping("/changeStatus")
	public @ResponseBody Map<String,Object> changeStatus(PartnerInfoVo entity,HttpServletResponse response) throws IOException{
		Map<String,Object> res = new HashMap<String, Object>();
		try {
			int count = mservice.update(entity);
			res.put("count",count);
			res.put("row",entity.toDto());
		}catch (YIXUNUNCheckedException e) {
			log.error("操作失败",e);
			res.put("errorMsg",e.getCode()+":"+e.getOutMsg());
		}catch (Exception e) {
			log.error("操作失败",e);
			res.put("errorMsg",YIXUNExceptionCode.UNKNOW_EXCEPTON.getDesout());
		}
		return res;
	}
	/**
	 * 根据公司获取人员列表
	 * @param entity
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/getPartnerList")
	public String companyList(PartnerInfoVo entity, HttpServletResponse response) throws IOException{
		entity.setStatus("1");
		entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<PartnerInfo> list = mservice.selectListByDto(entity.toDto());
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(JSONObject.toJSONString(list));
		return null;
	}
}
